/*
 * Copyright 2020-2023 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.security.oauth2.server.authorization.authentication;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.core.log.LogMessage;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClaimAccessor;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import org.springframework.security.oauth2.core.OAuth2Token;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.OidcScopes;
import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationCode;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.context.AuthorizationServerContextHolder;
import org.springframework.security.oauth2.server.authorization.token.DefaultOAuth2TokenContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import static org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthenticationProviderUtils.getAuthenticatedClientElseThrowInvalidClient;

/**
 * An {@link AuthenticationProvider} implementation for the OAuth 2.0 Authorization Code Grant.
 *
 * @author Joe Grandja
 * @author Daniel Garnier-Moiroux
 * @since 0.0.1
 * @see OAuth2AuthorizationCodeAuthenticationToken
 * @see OAuth2AccessTokenAuthenticationToken
 * @see OAuth2AuthorizationCodeRequestAuthenticationProvider
 * @see OAuth2AuthorizationService
 * @see OAuth2TokenGenerator
 * @see <a target="_blank" href="https://datatracker.ietf.org/doc/html/rfc6749#section-4.1">Section 4.1 Authorization Code Grant</a>
 * @see <a target="_blank" href="https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.3">Section 4.1.3 Access Token Request</a>
 */
public final class OAuth2AuthorizationCodeAuthenticationProvider implements AuthenticationProvider {
	private static final String ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-5.2";
	private static final OAuth2TokenType AUTHORIZATION_CODE_TOKEN_TYPE =
			new OAuth2TokenType(OAuth2ParameterNames.CODE);
	private static final OAuth2TokenType ID_TOKEN_TOKEN_TYPE =
			new OAuth2TokenType(OidcParameterNames.ID_TOKEN);
	private final Log logger = LogFactory.getLog(getClass());
	private final OAuth2AuthorizationService authorizationService;
	// 默认为DelegatingOAuth2TokenGenerator
	private final OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator;
	private SessionRegistry sessionRegistry;

	/**
	 * Constructs an {@code OAuth2AuthorizationCodeAuthenticationProvider} using the provided parameters.
	 *
	 * @param authorizationService the authorization service
	 * @param tokenGenerator the token generator
	 * @since 0.2.3
	 */
	public OAuth2AuthorizationCodeAuthenticationProvider(OAuth2AuthorizationService authorizationService,
			OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator) {
		Assert.notNull(authorizationService, "authorizationService cannot be null");
		Assert.notNull(tokenGenerator, "tokenGenerator cannot be null");
		this.authorizationService = authorizationService;
		this.tokenGenerator = tokenGenerator;
	}

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication =
				(OAuth2AuthorizationCodeAuthenticationToken) authentication;
		// 获取OAuth2ClientAuthenticationToken对象，并判断是否已认证 正常流程到达此处经过OAuth2ClientAuthenticationFilter此处应该是已认证状态
		OAuth2ClientAuthenticationToken clientPrincipal =
				getAuthenticatedClientElseThrowInvalidClient(authorizationCodeAuthentication);
		// 从OAuth2ClientAuthenticationToken对象中获取已认证的客户端信息，而该客户端信息是根据/oauth2/token请求中传递的clientId，clientSecret
		// 经过查询验证没问题后封装到该对象中的    但是这里就会存在一个掩埋的问题点：
		// 假如客户端获取授权码的请求是由A客户端发起的，然后黑客将授权码请求进行拦截获取到code,然后拿着code再拼接一个B客户端的信息，且B客户端是黑客以正常身份在授权端注册过的，
		// 那么在经过OAuth2ClientAuthenticationFilter客户端认证的时候由于B也在授权端注册过，所以其认证会没有问题，此时会将B的客户端信息封装到了
		// OAuth2ClientAuthenticationToken对象中  那么此时就会存在漏洞问题？？  springSecurity再生成code返回给客户端的时候，会将最原始的授权请求记录到oauth2_authorization
		// 中，根据code拿到原始的授权请求获取其发起请求的客户端信息 然后跟已认证的进行比对，如果不是同一个那么说明有问题，会进行处理
		RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();

		if (this.logger.isTraceEnabled()) {
			this.logger.trace("Retrieved registered client");
		}
		// 根据code从oauth2_authorization获取发放令牌记录信息(code生成时会往该表中存入数据) -- 相当于对code是否存在进行校验
		OAuth2Authorization authorization = this.authorizationService.findByToken(
				authorizationCodeAuthentication.getCode(), AUTHORIZATION_CODE_TOKEN_TYPE);
		// 如果为null，说明code有问题，异常抛出
		if (authorization == null) {
			throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_GRANT);
		}

		if (this.logger.isTraceEnabled()) {
			this.logger.trace("Retrieved authorization with authorization code");
		}
		// oauth2_authorization表中的数据包括code(也相当于一种token),idToken,refreshToken,accessToken等信息，每个token都包含了过期时间，是否有效
		// (元数据字段)，具体的tokenValue等值，所以在OAuth2Authorization中封装了一个类型为map的token集合，key是每种token对应的类型，value值为该token对应的基础信息
		// 此处获取的为code对应的基础信息集合
		OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCode =
				authorization.getToken(OAuth2AuthorizationCode.class);
		// 获取授权最原始的请求信息，即客户端向授权端发起的授权请求
		OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute(
				OAuth2AuthorizationRequest.class.getName());
		// 如果已认证的客户端(发起token请求传递过来的客户端信息)跟授权请求(发起code请求传递过来的客户端信息)中传递过来的不一致 那么会异常抛出
		if (!registeredClient.getClientId().equals(authorizationRequest.getClientId())) {
			// 如果此时code令牌是有效的 那么说明已被泄漏，将其无效化（metadata.token.invalidated键值对信息）
			if (!authorizationCode.isInvalidated()) {
				// Invalidate the authorization code given that a different client is attempting to use it
				// 如果另一个客户端试图使用授权码，则使其无效，再oauth2_authorization表中authorization_code_metadata字段中存在一个metadata.token.invalidated
				// 键值对，表示授权码状态
				authorization = OAuth2AuthenticationProviderUtils.invalidate(authorization, authorizationCode.getToken());
				this.authorizationService.save(authorization);
				if (this.logger.isWarnEnabled()) {
					this.logger.warn(LogMessage.format("Invalidated authorization code used by registered client '%s'", registeredClient.getId()));
				}
			}
			throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_GRANT);
		}
		// 最原始的授权请求中的重定向地址(redirectUri)不为null，且和token请求中的重定向地址不一致，异常抛出
		if (StringUtils.hasText(authorizationRequest.getRedirectUri()) &&
				!authorizationRequest.getRedirectUri().equals(authorizationCodeAuthentication.getRedirectUri())) {
			throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_GRANT);
		}
		// 如果code令牌当前处于非活动状态(无效的，过期的，已使用过) 则异常抛出
		if (!authorizationCode.isActive()) {
			// 如果令牌code已失效
			if (authorizationCode.isInvalidated()) {
				// 对refreshToken或者accessToken进行失效处理
				OAuth2Authorization.Token<? extends OAuth2Token> token = authorization.getRefreshToken() != null ?
						authorization.getRefreshToken() :
						authorization.getAccessToken();
				if (token != null) {
					// Invalidate the access (and refresh) token as the client is attempting to use the authorization code more than once
					// 当客户端试图多次使用授权码时，使访问(和刷新)令牌无效
					authorization = OAuth2AuthenticationProviderUtils.invalidate(authorization, token.getToken());
					this.authorizationService.save(authorization);
					if (this.logger.isWarnEnabled()) {
						this.logger.warn(LogMessage.format("Invalidated authorization token(s) previously issued to registered client '%s'", registeredClient.getId()));
					}
				}
			}
			throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_GRANT);
		}

		if (this.logger.isTraceEnabled()) {
			this.logger.trace("Validated token request parameters");
		}
		// 获取客户端授权请求获取code时使用的认证用户信息(再获取code后往oauth2_authorization表存数据的时候，将当前登录的用户信息principal也存入了该表中的attributes字段中)
		Authentication principal = authorization.getAttribute(Principal.class.getName());

		// @formatter:off
		// 将认证客户端信息，登录颁发code的用户信息，环境安全上下文，最原始的授权请求等填充的DefaultOAuth2TokenContext构建器中
		DefaultOAuth2TokenContext.Builder tokenContextBuilder = DefaultOAuth2TokenContext.builder()
				.registeredClient(registeredClient)
				.principal(principal)
				.authorizationServerContext(AuthorizationServerContextHolder.getContext())
				.authorization(authorization)
				.authorizedScopes(authorization.getAuthorizedScopes())
				.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
				.authorizationGrant(authorizationCodeAuthentication);
		// @formatter:on
		// 该builder用于存放所有信息，包含后面生成的accessToken和refreshToken和idToken，注意初始化的参数为oauth2_authorization表中数据集合
		// 此时的authorization.tokens集合中仅包含code令牌信息
		OAuth2Authorization.Builder authorizationBuilder = OAuth2Authorization.from(authorization);

		// ----- Access token -----
		// 构建access_token对应的tokenContext对象
		OAuth2TokenContext tokenContext = tokenContextBuilder.tokenType(OAuth2TokenType.ACCESS_TOKEN).build();
		// 生成access_token 返回JWT对象或者OAuth2AccessTokenClaims对象  取决于oauth2_registered_client.token_settings.access-token-format的值，
		// 当其为reference时返回OAuth2AccessTokenClaims 当其为self-contained时返回JWT对象(默认采用该方式和idToken使用一样的生成器)
		OAuth2Token generatedAccessToken = this.tokenGenerator.generate(tokenContext);
		// 如果为null，则access_token生成失败 异常抛出
		if (generatedAccessToken == null) {
			OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR,
					"The token generator failed to generate the access token.", ERROR_URI);
			throw new OAuth2AuthenticationException(error);
		}

		if (this.logger.isTraceEnabled()) {
			this.logger.trace("Generated access token");
		}
		//  Bearer, 只有OAuth2AccessToken这里有tokenType ，可设置为Bearer，其传递时一般都是放在请求头中
		// 下面的OAuth2RefreshToken和OidcIdToken没有该选项 一般accessToken通过header中Authorization字段携带
		// 而refreshToken作为cookie或local storage保存在浏览器中 idToken一般供后端使用，不像前端展示
		OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
				generatedAccessToken.getTokenValue(), generatedAccessToken.getIssuedAt(),
				generatedAccessToken.getExpiresAt(), tokenContext.getAuthorizedScopes());
		//JWT对象是ClaimAccessor的实现类 此处将生成的声明信息填充的oauth2_authorization表中access_token_metadata字段
		//OAuth2AccessTokenClaims对象也符合该条件  需要注意的是generatedAccessToken中是存在Claims(包含用户名称，认证客户端id等信息)，但是再上面生成的accessToken
		//中是没有封装这一部分数据的，而是将这部分声明信息存到了数据库中
		if (generatedAccessToken instanceof ClaimAccessor) {
			authorizationBuilder.token(accessToken, (metadata) ->
					metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, ((ClaimAccessor) generatedAccessToken).getClaims()));
		} else {
			// 加入authorizationBuilder
			authorizationBuilder.accessToken(accessToken);
		}

		// ----- Refresh token -----
		OAuth2RefreshToken refreshToken = null;
		//认证的客户端信息(数据库{oauth2_registered_client}或者内存在获取的)是否包含refresh_token(令牌刷新模式)
		if (registeredClient.getAuthorizationGrantTypes().contains(AuthorizationGrantType.REFRESH_TOKEN)) {
			// 构建refresh_token对应的tokenContext对象
			tokenContext = tokenContextBuilder.tokenType(OAuth2TokenType.REFRESH_TOKEN).build();
			// 生成refresh_token 返回OAuth2RefreshToken对象
			OAuth2Token generatedRefreshToken = this.tokenGenerator.generate(tokenContext);
			if (generatedRefreshToken != null) {
				if (!(generatedRefreshToken instanceof OAuth2RefreshToken)) {
					OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR,
							"The token generator failed to generate a valid refresh token.", ERROR_URI);
					throw new OAuth2AuthenticationException(error);
				}

				if (this.logger.isTraceEnabled()) {
					this.logger.trace("Generated refresh token");
				}

				refreshToken = (OAuth2RefreshToken) generatedRefreshToken;
				// 加入authorizationBuilder
				authorizationBuilder.refreshToken(refreshToken);
			}
		}

		// ----- ID token -----
		OidcIdToken idToken;
		// 授权请求中范围包含openid，则生成idToken--用来认证
		if (authorizationRequest.getScopes().contains(OidcScopes.OPENID)) {
			// 获取当前主体(认证用户)对应的最近使用的session信息(注意一个principal可以有多个session，比如同一用户多个浏览器登录)
			SessionInformation sessionInformation = getSessionInformation(principal);
			if (sessionInformation != null) {
				try {
					// Compute (and use) hash for Session ID
					// 创建一个新的SessionInformation，将最近使用的sessionId进行编码加密
					sessionInformation = new SessionInformation(sessionInformation.getPrincipal(),
							createHash(sessionInformation.getSessionId()), sessionInformation.getLastRequest());
				} catch (NoSuchAlgorithmException ex) {
					OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR,
							"Failed to compute hash for Session ID.", ERROR_URI);
					throw new OAuth2AuthenticationException(error);
				}
				tokenContextBuilder.put(SessionInformation.class, sessionInformation);
			}
			// @formatter:off
			// 构建id_token对应的tokenContext对象
			tokenContext = tokenContextBuilder
					.tokenType(ID_TOKEN_TOKEN_TYPE)
					//注意这里将OAuth2Authorization对象里面包含刚生成的access token和refresh token 也封装到了tokenContext对象中
					.authorization(authorizationBuilder.build())	// ID token customizer may need access to the access token and/or refresh token
					.build();
			// @formatter:on
			// 生成id_token 返回Jwt对象
			OAuth2Token generatedIdToken = this.tokenGenerator.generate(tokenContext);
			if (!(generatedIdToken instanceof Jwt)) {
				OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR,
						"The token generator failed to generate the ID token.", ERROR_URI);
				throw new OAuth2AuthenticationException(error);
			}

			if (this.logger.isTraceEnabled()) {
				this.logger.trace("Generated id token");
			}
			// 将idToken相关的信息封装成OidcIdToken对象 generatedIdToken.getTokenValue()是一个jws(signedJwt.serialize())
			idToken = new OidcIdToken(generatedIdToken.getTokenValue(), generatedIdToken.getIssuedAt(),
					generatedIdToken.getExpiresAt(), ((Jwt) generatedIdToken).getClaims());
			// OidcIdToken封装到OAuth2Authorization的构建器中，且将idToken的声明信息放入了oidc_id_token_metadata字段中
			authorizationBuilder.token(idToken, (metadata) ->
					metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims()));
		} else {
			// 如果不包含openId，直接返回null
			idToken = null;
		}
		// 通过构建器构建OAuth2Authorization对象，此时里面Map<Class<? extends OAuth2Token>, Token<?>> tokens属性集合包含我们刚才生成的各种token信息
		authorization = authorizationBuilder.build();

		// Invalidate the authorization code as it can only be used once
		// 此时各种token均以生成，使授权码无效，因为它只能使用一次 即metadata.token.invalidated设置为true
		authorization = OAuth2AuthenticationProviderUtils.invalidate(authorization, authorizationCode.getToken());
		// 保存已完成的Authorization，包含各个token的元数据，以及code元数据失效等信息更新到oauth2_authorization
		this.authorizationService.save(authorization);

		if (this.logger.isTraceEnabled()) {
			this.logger.trace("Saved authorization");
		}
		//如果idToken不为null，就将其封装到一个额外参数集合中，客户端也是从该Map集合中获取的idToken
		Map<String, Object> additionalParameters = Collections.emptyMap();
		if (idToken != null) {
			additionalParameters = new HashMap<>();
			additionalParameters.put(OidcParameterNames.ID_TOKEN, idToken.getTokenValue());
		}

		if (this.logger.isTraceEnabled()) {
			this.logger.trace("Authenticated token request");
		}
		// 将认证的客户端，各种token信息封装成OAuth2AccessTokenAuthenticationToken对象  注意该对象未认证
		return new OAuth2AccessTokenAuthenticationToken(
				registeredClient, clientPrincipal, accessToken, refreshToken, additionalParameters);
	}

	@Override
	public boolean supports(Class<?> authentication) {
		return OAuth2AuthorizationCodeAuthenticationToken.class.isAssignableFrom(authentication);
	}

	/**
	 * Sets the {@link SessionRegistry} used to track OpenID Connect sessions.
	 *
	 * @param sessionRegistry the {@link SessionRegistry} used to track OpenID Connect sessions
	 * @since 1.1
	 */
	public void setSessionRegistry(SessionRegistry sessionRegistry) {
		Assert.notNull(sessionRegistry, "sessionRegistry cannot be null");
		this.sessionRegistry = sessionRegistry;
	}

	private SessionInformation getSessionInformation(Authentication principal) {
		SessionInformation sessionInformation = null;
		if (this.sessionRegistry != null) {
			//获取当前主体所有的有效session信息
			List<SessionInformation> sessions = this.sessionRegistry.getAllSessions(principal.getPrincipal(), false);
			if (!CollectionUtils.isEmpty(sessions)) {
				sessionInformation = sessions.get(0);
				if (sessions.size() > 1) {
					// Get the most recent session
					sessions = new ArrayList<>(sessions);
					sessions.sort(Comparator.comparing(SessionInformation::getLastRequest));
					sessionInformation = sessions.get(sessions.size() - 1);
				}
			}
		}
		return sessionInformation;
	}

	private static String createHash(String value) throws NoSuchAlgorithmException {
		MessageDigest md = MessageDigest.getInstance("SHA-256");
		byte[] digest = md.digest(value.getBytes(StandardCharsets.US_ASCII));
		return Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
	}

}
